//
//  SISSEscrowAccountShowViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2018/10/25.
//  Copyright © 2018年 优房网. All rights reserved.
//

#import "SISSEscrowAccountShowViewController.h"
#import "SISSEscrowAccountShowViewModel.h"
#import "SISSEscrowAccountApplyViewController.h"
#import "SISSHouseProgressViewController.h"
#import "SISSNetworkingManager+HouseProgress.h"
#import "SISSNetworkingManager+PassengerProgress.h"
#import "SISSPassengerProgressViewController.h"
#import "SISSHouseRelevantModel.h"
#import "SISSHouseProgressRecordInfoModel.h"
#import "SISSPassengerProgressModel.h"
#import "SISSPassengerProgressRecordInfoModel.h"
#import "SISSBuyerInfoModel.h"

@interface SISSEscrowAccountShowViewController ()

@property (strong, nonatomic) SISSEscrowAccountShowViewModel *escrowAccountShowViewModel;
/// 编辑按钮
@property (weak, nonatomic) UIButton *editButton;
@property (copy, nonatomic) void(^complete)();

@end

@implementation SISSEscrowAccountShowViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"资金监管帐户申请";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemAction)];
    
    [self requestData];
    
}

/**
 返回按钮点击事件
 */
- (void)backItemAction {
    for (UIViewController *controller in self.navigationController.viewControllers) {
        if ([controller isKindOfClass:[SISSHouseProgressViewController class]] || [controller isKindOfClass:[SISSPassengerProgressViewController class]]) {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}

- (void)requestData {
    NSString *ahbpId = self.houseProgressModel ? self.houseProgressModel.ahbpId : self.passengerProgressRecordInfoModel.ahbpId;
    
    [kNetworkManager requestFundSupervisionInfoWithAhbpId:ahbpId success:^(SISSEscrowAccountInfoModel *ecrowAccountInfoModel) {
        self.ecrowAccountInfoModel = ecrowAccountInfoModel;
        if (ecrowAccountInfoModel) {
            [self.escrowAccountShowViewModel assignmentWithEscrowAccountInfoModel:ecrowAccountInfoModel];
            [self requestSellerAndBuyerInfo];
        } else if (self.isHistory && !ecrowAccountInfoModel) {
            for (UIView *view in self.view.subviews) {
                view.hidden = YES;
            }
        }
        
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)requestSellerAndBuyerInfo {
    WeakSelf
    __block NSInteger requestCount = 0;
    NSString *ahbpId = self.houseProgressModel ? self.houseProgressModel.ahbpId : self.passengerProgressRecordInfoModel.ahbpId;
    NSInteger houseType = self.houseProgressModel ? self.houseProgressModel.houseresType : self.passengerProgressRecordInfoModel.house_type;
    [kNetworkManager requestProgressSellerInfoWithAhbpId:ahbpId houseType:houseType success:^(SISSSellerInfoModel *sellerInfoModel) {
        self.escrowAccountShowViewModel.dataArr[0][0].rightStr = sellerInfoModel.seller_name;
        self.escrowAccountShowViewModel.dataArr[0][1].rightStr = sellerInfoModel.idNo;
        requestCount++;
        if (self.complete) {
            self.complete();
        }
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    NSString *adbpId = self.houseProgressModel ? self.houseProgressRecordInfoModel.adbpId : self.passengerProgressModel.adbpId;
    NSInteger demandType = self.houseProgressModel ? self.houseProgressRecordInfoModel.demand_type : self.passengerProgressModel.demandType;
    [kNetworkManager requestrProgressBuyerInfoWithAdbpId:adbpId demandType:demandType success:^(SISSBuyerInfoModel *buyerInfoModel) {
        
        self.escrowAccountShowViewModel.dataArr[1][0].rightStr = buyerInfoModel.buyer_name;
        self.escrowAccountShowViewModel.dataArr[1][1].rightStr = buyerInfoModel.idNo;
        requestCount++;
        if (self.complete) {
            self.complete();
        }
    } failed:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    self.complete = ^{
        if (requestCount == 2) {
            //在这里 进行请求后的方法，回到主线程
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableView reloadData];
            });
        }
    };
}

#pragma mark - 代理
#pragma mark -- UITableViewDelegate & UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.escrowAccountShowViewModel getSectionCount];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.escrowAccountShowViewModel getRowsInSection:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [self.escrowAccountShowViewModel getCell:tableView indexPath:indexPath];
    cell.userInteractionEnabled = NO;
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}



- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return [self.escrowAccountShowViewModel getHeightForHeaderInSection:section];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return [self.escrowAccountShowViewModel getViewHeaderInSection:section];
}

// 取消tableView组头悬停
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 40;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}


- (void)editButtonClickAction {
    SISSEscrowAccountApplyViewController *vc = [[SISSEscrowAccountApplyViewController alloc] init];
    vc.dataSource = self.escrowAccountShowViewModel.dataArr;
    vc.escrowAccountInfoModel = self.ecrowAccountInfoModel;
    vc.houseProgressModel = self.houseProgressModel;
    vc.houseProgressRecordInfoModel = self.houseProgressRecordInfoModel;
    vc.passengerProgressModel = self.passengerProgressModel;
    vc.passengerProgressRecordInfoModel = self.passengerProgressRecordInfoModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UI
- (void)setupSubviews {
    [super setupSubviews];
    
    self.escrowAccountShowViewModel = [[SISSEscrowAccountShowViewModel alloc] init];
    if (self.dataSource.count > 0) {
        self.escrowAccountShowViewModel.dataArr = self.dataSource.copy;
    }
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] init];
    tableView.estimatedRowHeight = 44;
    tableView.rowHeight = UITableViewAutomaticDimension;
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.escrowAccountShowViewModel registContractClass:tableView];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    self.escrowAccountShowViewModel.tableView = tableView;
    
    UIView *footerView = [[UIView alloc ] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 88)];
    UIButton *editButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [editButton setTitle:@"编辑" forState:UIControlStateNormal];
    [editButton setBackgroundColor:MAIN_COLOR];
    [editButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [editButton addTarget:self action:@selector(editButtonClickAction) forControlEvents:UIControlEventTouchUpInside];
    editButton.layer.cornerRadius = 4;
    editButton.layer.masksToBounds = YES;
    [footerView addSubview:editButton];
    self.editButton = editButton;
    
    [self.editButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(footerView);
        make.width.mas_equalTo(SCREEN_WIDTH * 0.7);
        make.height.mas_equalTo(44);
    }];
    self.tableView.tableFooterView = footerView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self.view endEditing:YES];
}

@end
